package com.voicechat.firstmet.imcontrol;

import android.content.Context;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.tencent.TIMFriendshipManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageStatus;
import com.tencent.TIMUserProfile;
import com.tencent.TIMValueCallBack;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.PersonalHomepageActivity;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息数据基类
 */
public abstract class Message implements Parcelable{

    protected final String TAG = "Message";

    TIMMessage message;

    private boolean hasTime;

    /**
     * 消息描述信息
     */
    private String desc;


    public TIMMessage getMessage() {
        return message;
    }


    /**
     * 显示消息
     *
     * @param viewHolder 界面样式
     * @param context 显示消息的上下文
     */
    public abstract void showMessage(ChatAdapter.ViewHolder viewHolder, Context context);

    /**
     * 获取显示气泡
     *
     * @param viewHolder 界面样式
     */
    public RelativeLayout getBubbleView(ChatAdapter.ViewHolder viewHolder){
        viewHolder.systemMessage.setVisibility(hasTime? View.VISIBLE: View.GONE);

        String format = "yyyy" + App.getContext().getResources().getString(R.string.time_year) + "MM" + App.getContext().getResources().getString(R.string.time_month) + "dd" + App.getContext().getResources().getString(R.string.time_day) + " HH:mm";
        viewHolder.systemMessage.setText(Utils.getChatTimeStr(message.timestamp(),format));
        //showDesc(viewHolder);
        if (message.isSelf()){
            viewHolder.leftPanel.setVisibility(View.GONE);
            viewHolder.rightPanel.setVisibility(View.VISIBLE);
            getUserMessage(viewHolder);
            return viewHolder.rightMessage;
        }else{
            viewHolder.leftPanel.setVisibility(View.VISIBLE);
            viewHolder.rightPanel.setVisibility(View.GONE);
            TIMUserProfile senderProfile = message.getSenderProfile();
            getUserMessageOther(senderProfile.getIdentifier(),viewHolder);
            //Glide.with(App.getContext()).load(faceUrl).into(viewHolder.leftAvatar);
            return viewHolder.leftMessage;
        }
    }
    /**
     * @method
     * @description 获取自己资料
     * @date: 2018/11/9 11:10
     * @author: ljp
     * @return
     */
    private void   getUserMessage(ChatAdapter.ViewHolder viewHolder){
        //获取自己的资料
        TIMFriendshipManager.getInstance().getSelfProfile(new TIMValueCallBack<TIMUserProfile>(){
            @Override
            public void onError(int code, String desc){
                //错误码 code 和错误描述 desc，可用于定位请求失败原因
                //错误码 code 列表请参见错误码表
                Log.e(TAG, "getSelfProfile failed: " + code + " desc");
                return;
            }
            @Override
            public void onSuccess(TIMUserProfile result){
                //Log.e(tag, "getSelfProfile succ");
               // Log.e(TAG, "getUserMessage: " + result.getIdentifier() + " nickName: " + result.getNickName()
                  //      + " remark: " + result.getRemark() + " allow: " + result.getAllowType()+"-getFaceUrl--"+result.getFaceUrl());
                String[] strings = Utils.spitInfo(result.getFaceUrl());
                // 头像地址 + 是否会员 + 是否主播 + 生日
                if (!strings[0].equals(viewHolder.rightAvatar.getTag(R.id.rightAvatar))) {
                    // 加载图片
                    viewHolder.rightAvatar.setTag(R.id.rightAvatar, strings[0]);
                    GlideLoadUtils.getInstance().glideLoad(App.getContext(),OssConfig.OSS_HTTP+strings[0],
                            viewHolder.rightAvatar);
                }

                //Glide.with(App.getContext()).load(OssConfig.OSS_HTTP+strings[0]).into(viewHolder.rightAvatar);
            }
        });
    }
    /**
     * @method
     * @description 获取别人资料
     * @date: 2018/11/9 11:10
     * @author: ljp
     * @return
     */
    private void getUserMessageOther(String id,ChatAdapter.ViewHolder viewHolder) {
        //待获取用户资料的用户列表
        List<String> users = new ArrayList<String>();
        users.add(id);
        //获取用户资料
        TIMFriendshipManager.getInstance().getUsersProfile(users, new TIMValueCallBack<List<TIMUserProfile>>() {
            @Override
            public void onError(int code, String desc) {
                //错误码 code 和错误描述 desc，可用于定位请求失败原因
                //错误码 code 列表请参见错误码表
                Log.e(TAG, "getUsersProfile failed: " + code + " desc");
            }
            @Override
            public void onSuccess(List<TIMUserProfile> result) {
                //Log.e(TAG, "getUsersProfile succ");
                for (TIMUserProfile res : result) {
                   /* Log.e(TAG, "identifier: " + res.getIdentifier() + " nickName: " + res.getNickName()
                            + " getFaceUrl: " + res.getFaceUrl());*/
                    String[] strings = Utils.spitInfo(res.getFaceUrl());
                    //Log.i(TAG, "onSuccess: --"+strings[0]);
                    // 头像地址 + 是否会员 + 是否主播 + 生日
                    if (!strings[0].equals(viewHolder.leftAvatar.getTag(R.id.leftAvatar))) {
                        // 加载图片
                        viewHolder.leftAvatar.setTag(R.id.leftAvatar, strings[0]);
                        GlideLoadUtils.getInstance().glideLoad(App.getContext(),OssConfig.OSS_HTTP+strings[0],
                                viewHolder.leftAvatar);
                    }
                   // Glide.with(App.getContext()).load(OssConfig.OSS_HTTP+strings[0]).into(viewHolder.leftAvatar);
                }
            }
        });
    }

    /**
     * 显示消息状态
     *
     * @param viewHolder 界面样式
     */
    public void showStatus(ChatAdapter.ViewHolder viewHolder){
        switch (message.status()){
            case Sending:
                //viewHolder.error.setVisibility(View.GONE);
                viewHolder.sending.setVisibility(View.VISIBLE);
                break;
            case SendSucc:
               // viewHolder.error.setVisibility(View.GONE);
                viewHolder.sending.setVisibility(View.GONE);
                break;
            case SendFail:
                //viewHolder.error.setVisibility(View.VISIBLE);
                viewHolder.sending.setVisibility(View.GONE);
                viewHolder.leftPanel.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 判断是否是自己发的
     *
     */
    public boolean isSelf(){
        return message.isSelf();
    }
    /**
     * 判断消息是否已读
     *
     */
    public boolean isRead(){
        return message.isRead();
    }

    /**
     * 获取消息摘要
     *
     */
    public abstract String getSummary();

    /**
     * 保存消息或消息文件
     *
     */
    public abstract void save();


    /**
     * 删除消息
     *
     */
    public void remove(){
        if (message != null){
            message.remove();
        }
    }



    /**
     * 是否需要显示时间获取
     *
     */
    public boolean getHasTime() {
        return hasTime;
    }


    /**
     * 是否需要显示时间设置
     *
     * @param message 上一条消息
     */
    public void setHasTime(TIMMessage message){
        if (message == null){
            hasTime = true;
            return;
        }
        hasTime = this.message.timestamp() - message.timestamp() > 300;
    }
    /**
     * 跳转到聊天界面或会话详情
     *
     */
     public void navToPerson(Context context,String id){
         PersonalHomepageActivity.navToChat(context,id);
    }

    /**
     * 消息是否发送失败
     *
     */
    public boolean isSendFail(){
        return message.status() == TIMMessageStatus.SendFail;
    }

    /**
     * 清除气泡原有数据
     *
     */
    protected void clearView(ChatAdapter.ViewHolder viewHolder){
        getBubbleView(viewHolder).removeAllViews();
        getBubbleView(viewHolder).setOnClickListener(null);
    }

    /**
     * 获取发送者
     *
     */
    public String getSender(){
        if (message.getSender() == null) return "";
        return message.getSender();
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }


    private void showDesc(ChatAdapter.ViewHolder viewHolder){

        if (desc == null || desc.equals("")){
            viewHolder.rightDesc.setVisibility(View.GONE);
        }else{
            viewHolder.rightDesc.setVisibility(View.VISIBLE);
            viewHolder.rightDesc.setText(desc);
        }
    }
}
